package com.zhq.security.auth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class FailHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException, IOException {
        // 设置response缓冲区字符集
        response.setCharacterEncoding("UTF-8");
        // 定义一个JSONObject对象
        Map<String,String> object = new HashMap<>();
        // 填写登录失败响应信息
        object.put("code", "-1");
        object.put("msg", "登录失败");
        // 设置响应头
        response.setContentType("application/json;charset=utf-8");
        // 获得打印输出流
        PrintWriter pw = response.getWriter();
        // 向客户端写入一个字符串
        pw.print(object.toString());
        pw.write(new ObjectMapper().writeValueAsString(object));
        pw.flush();
        // 关闭流资源
        pw.close();
    }
}